
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:speex_demo/speex_ffi.dart';
import 'package:speex_demo/xf_iat_stream.dart';

import 'derucci_iat_stream.dart';

///单次定时
timer(int milliseconds, void Function() fun) {
  return Timer(Duration(milliseconds: milliseconds), fun);
}

class RecordDemo {
  // 1. 静态成员：late final + 私有构造函数，直接赋值初始化
  static final RecordDemo instance = RecordDemo._();

  // 2. 私有构造函数：禁止外部实例化
  RecordDemo._();

  bool _isRecording = false;
  int frameState = 0;
  final FlutterSoundRecorder _recorder = FlutterSoundRecorder();
  Stream<Uint8List>? _audioStream;
  StreamController<Uint8List>? _audioStreamController;
  final BytesBuilder _pcmBuffer = BytesBuilder();
  final BytesBuilder _audioBuffer = BytesBuilder();
  final StringBuffer _base64Buffer = StringBuffer();
  late DerucciIatStream xf;

  getAudioBuffer() {
    return _audioBuffer;
  }

  Future<void> initRecorder() async {
    await _recorder.openRecorder();
  }

  stopRecord() async {
    if(_isRecording) {
      await _recorder.stopRecorder();
      frameState = 2;
      xf.startRecognize(null, frameState);
      timer(5000, () async {
        _audioStreamController?.close();
        _audioStreamController = null;
        _audioStream = null;
        _isRecording = false;
      });
      return;
    }
  }

  startRecord() async {
    if(_isRecording) {
      return;
    }
    xf = DerucciIatStream();
    _audioBuffer.clear();
    _pcmBuffer.clear();
    _base64Buffer.clear();
    _isRecording = true;
    _audioStreamController = StreamController<Uint8List>();
    _audioStream = _audioStreamController!.stream;
    _recorder.startRecorder(
      toStream: _audioStreamController!.sink,
      codec: Codec.pcm16, // PCM16原始数据
      numChannels: 1,     // 单声道
      sampleRate: 16000,  // 16k采样率
    );
    final encoder = SpeexEncoderFFI();
    final frameSize = encoder.frameSize * 2; // 16-bit PCM
    Uint8List buffer = Uint8List(0);
    frameState = 0;
    Future<void> recognitionQueue = Future.value();
    _audioStream!.listen((Uint8List data) {
      _pcmBuffer.add(data);
      buffer = Uint8List.fromList([...buffer, ...data]);
      while (buffer.length >= frameSize) {
        final frame = buffer.sublist(0, frameSize);
        final encoded = encoder.encode(frame);
        recognitionQueue = recognitionQueue.then((_) async {
          await xf.startRecognize(encoded, frameState);
          frameState = 1;
          _audioBuffer.add(encoded);
        });
        buffer = buffer.sublist(frameSize);
      }
    });
  }
}


Future<void> uploadFile(Uint8List data, String fileName) async {
  try {
    // 1. 获取临时目录
    final tempDir = await getTemporaryDirectory();
    final filePath = '${tempDir.path}/$fileName';

    // 2. 将 Uint8List 写入本地文件
    final file = File(filePath);
    await file.writeAsBytes(data);

    // 3. 上传文件
    final dio = Dio();
    final formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(filePath, filename: fileName),
    });

    final response = await dio.post(
      'http://10.34.41.160:8888/upload',
      data: formData,
    );

    print('上传成功: ${response.data}');
  } catch (e) {
    print('上传失败: $e');
  }
}
